package logic

import (
	"context"
	"errors"
	"novel/models/cache"
	"novel/models/mysql"
	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"
	"novel/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码
func (l *ForgetPasswordLogic) ForgetPassword(in *novelrpc.ForgetPasswordRequest) (*novelrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FirstUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, errors.New("用户不存在,不能重置密码")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if in.SendSmsCode == "" {
		return nil, errors.New("请输入验证码")
	}
	if result != in.SendSmsCode {
		return nil, errors.New("验证码错误")
	}
	if in.Password != in.NewPassword {
		return nil, errors.New("两次密码不一致")
	}
	user.Password = pkg.Md5(in.Password)
	err = user.ForgetPassword(mysql.DB)
	if err != nil {
		return nil, errors.New("重置密码失败")
	}

	return &novelrpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
